package top.hzy520.sms.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.hzy520.common.constants.Constants;
import top.hzy520.common.exception.YuYuBuyException;
import top.hzy520.common.util.RandomNumber;
import top.hzy520.common.util.RedisUtil;
import top.hzy520.jms.MessageProcessor;

import javax.jms.Destination;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 14:37 2018/5/29
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private MessageProcessor messageProcessor;

    @Autowired
    private RedisUtil redisUtil;
    private static final String SMS_QUEUE = "sms.queue";

    @Override
    public void sendSms(String mobile, String ip) throws UnsupportedEncodingException {
        if (mobile==null){
            throw new YuYuBuyException("手机号为空");
        }
        String code=RandomNumber.getRandomVerifyCode();
        //1.验证手机号和设备的可用性
         int result=redisUtil.setSmsVerifyCode(mobile,code,ip,60,".verify");
         if (result==1){
             log.error("验证码还未过期");
             throw new YuYuBuyException("验证码还未过期");
         }else if (result==2){
             log.error("手机号超过使用次数");
             throw new YuYuBuyException("手机号超过使用次数");
         }else if (result==3){
             log.error("设备超过使用次数");
             throw new YuYuBuyException("设备超过使用次数");
         }
        //2.拼装参数
        //3.调用mq异步发送短信
        Destination destination=new ActiveMQQueue(SMS_QUEUE);
        Map<String,String> map=new HashMap<>();
        map.put("mobile",mobile);
        map.put("tplId",Constants.MDSMS_VERCODE_TPLID);
        map.put("param",code);
        String param=JSON.toJSONString(map);
        messageProcessor.sendMesasageToQueue(destination,param);
    }

    @Override
    public boolean verifyCode(String mobile, String code) {
        if (code==null&&mobile==null){
            throw new YuYuBuyException("参数不合法");
        }
      String verifyCode=redisUtil.getMobileVerifyCode(mobile);
        if (verifyCode.equals(code)){
            return true;
        }
        log.info(mobile+"的用户:验证码不正确");
        return false;
    }

}
